package com.wgzx.modbus.handler;

import com.wgzx.modbus.constant.ModbusConstants;
import com.wgzx.modbus.factory.CodecFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ModbusChannelInitializer extends ChannelInitializer<Channel> {

    private final CodecFactory codecFactory;
    private final ModbusResponseHandler responseHandler;
    private final boolean enableLog;

    public ModbusChannelInitializer(CodecFactory codecFactory, ModbusResponseHandler responseHandler) {
        this(codecFactory, responseHandler, false);
    }

    public ModbusChannelInitializer(CodecFactory codecFactory, ModbusResponseHandler responseHandler, boolean enableLog) {
        this.codecFactory = codecFactory;
        this.responseHandler = responseHandler;
        this.enableLog = enableLog;
    }

    @Override
    protected void initChannel(Channel channel) {
        ChannelPipeline p = channel.pipeline();
        if(enableLog) {
            p.addLast("logHandler", new LoggingHandler(LogLevel.INFO));
        }
        p.addLast("lfbfDecoder", new LengthFieldBasedFrameDecoder(ModbusConstants.ADU_MAX_LENGTH, 4, 2));
        p.addLast("encoder", codecFactory.getModbusEncoder());
        p.addLast("decoder", codecFactory.getModbusDecoder());
        p.addLast("responseHandler", responseHandler);
    }

}
